package com.zmx.patients.view.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zmx.patients.BaseActivity;
import com.zmx.patients.R;
import com.zmx.patients.adapter.GoodsCartAdapter;
import com.zmx.patients.okhttp.OkHttp3ClientManager;
import com.zmx.patients.pojo.MallGoods;
import com.zmx.patients.utils.AllUtil;
import com.zmx.patients.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class ShoppingCartActivity extends BaseActivity implements GoodsCartAdapter.AddSubtractNumberListener {


    @BindView(R.id.empty_image)
    ImageView emptyImage;
    @BindView(R.id.re_view)
    RecyclerView reView;
    @BindView(R.id.total_price)
    TextView totalPrices;
    @BindView(R.id.submit)
    Button submit;

    private GoodsCartAdapter adapter;
    private List<MallGoods> lists;

    private BigDecimal totalPrice;//总价
    private int totalNumber = 0;//总数

    private Integer cancel_logo = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shopping_cart;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);

        adapter = new GoodsCartAdapter(mActivity, handler,1);
        adapter.setAddSubtractNumberListener(this);
        lists = new ArrayList<>();
        reView.setLayoutManager(new LinearLayoutManager(mActivity));
        reView.setAdapter(adapter);

    }

    @Override
    protected void onResume() {
        super.onResume();
        getCart();
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    try {

                        lists.clear();
                        JSONObject object = new JSONObject(msg.obj.toString());

                        if (object.getInt("code") == 1) {

                            JSONArray data = object.getJSONArray("data");
                            Gson gson = new Gson();
                            double price = 0;
                            for (int i = 0; i < data.length(); i++) {

                                MallGoods mg = gson.fromJson(data.getJSONObject(i).toString(), MallGoods.class);
                                lists.add(mg);
                                price = mg.getPrice() * mg.getNums() + price;
                                totalNumber = totalNumber + mg.getNums();

                            }
                            totalPrice = new BigDecimal(price);
                            totalPrice = totalPrice.setScale(2, RoundingMode.HALF_UP);
                            totalPrices.setText(Html.fromHtml("合计：<font color='#FF0000'>" + totalPrice + "</font>"));
                            if (totalNumber == 0) {

                                submit.setText("结算");
                            } else {

                                submit.setText("结算（" + totalNumber + "）");
                            }
                            adapter.setListAndNotifyDataSetChanged(lists);

                        } else {

                            emptyImage.setVisibility(View.VISIBLE);

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;
                case 3:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;

                case 2:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        if (object.getInt("code") == 1) {

                            if (cancel_logo == 0){
                                lists.get(position).setNums(num);

                                if (logo == 1) {

                                    totalPrice = totalPrice.add(new BigDecimal(lists.get(position).getPrice()));
                                    totalNumber = totalNumber + 1;

                                } else {

                                    totalPrice = totalPrice.subtract(new BigDecimal(lists.get(position).getPrice()));
                                    totalNumber = totalNumber - 1;

                                }


                                totalPrice = totalPrice.setScale(2, RoundingMode.HALF_UP);
                                totalPrices.setText(Html.fromHtml("合计：<font color='#FF0000'>" + totalPrice + "</font>"));
                                submit.setText("结算（" + totalNumber + "）");
                                adapter.notifyDataSetChanged();

                            }else{
                                getCart();
                            }

                        } else {

                            Toast(object.getString("msg"));

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 4:

                    String gid = msg.obj.toString();
                    AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                    builder.setTitle("是否移除该商品？");
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            dialog.dismiss();
                        }
                    });
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            cancel_logo = 1;
                            editCart(gid + "", "0");
                            dialog.dismiss();

                        }
                    });
                    builder.show();


                    break;

            }

        }
    };

    public void getCart() {

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(null)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getCart");
        params.put("data[]", "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 1, 404);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private Integer position, num, logo;

    @Override
    public void setaddNumberListener(Integer gid, Integer num, Integer position, Integer logo) {
        this.position = position;
        this.logo = logo;
        cancel_logo = 0;
        if (logo == 1) {

            this.num = num + 1;
            editCart(gid + "", (num + 1) + "");

        } else {

            this.num = num - 1;
            editCart(gid + "", (num - 1) + "");

        }
    }


    public void editCart(String goods_id, String nums) {

        List<String> l = new ArrayList<>();
        l.add(goods_id);
        l.add(nums + "");

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "editCart");
        params.put("data[goods_id]", goods_id);
        params.put("data[nums]", nums + "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 2, 404);

    }

    @OnClick(R.id.submit)
    public void onViewClicked() {

        Bundle bundle = new Bundle();
        bundle.putSerializable("lists", (Serializable) lists);
        startActivity(GoodsPaymentActivity.class,bundle);

    }
}
